#region Imports

using System;
using System.Collections.Generic;

#endregion

namespace MammothMicro.SilverSocket.Server
{
    /// <summary>
    /// The client registry.
    /// </summary>
    public class ClientRegistry
    {
        /// <summary>
        /// The clients.
        /// </summary>
        private readonly SortedDictionary<Guid, Client> clients = new SortedDictionary<Guid, Client>();

        /// <summary>
        /// The sync lock.
        /// </summary>
        private readonly object syncLock = new object();

        /// <summary>
        /// The add.
        /// </summary>
        /// <param name="client">
        /// </param>
        public void Add(Client client)
        {
            lock (this.syncLock)
            {
                this.clients.Add(client.Id, client);
            }
        }

        /// <summary>
        /// The contains.
        /// </summary>
        /// <param name="clientId">
        /// </param>
        /// <returns>
        /// The contains.
        /// </returns>
        public bool Contains(Guid clientId)
        {
            return this.clients.ContainsKey(clientId);
        }

        /// <summary>
        /// The get all.
        /// </summary>
        /// <returns>
        /// </returns>
        public IList<Client> GetAll()
        {
            var list = new List<Client>();
            foreach (var pair in this.clients)
            {
                list.Add(pair.Value);
            }

            return list.AsReadOnly();
        }

        /// <summary>
        /// The get by id.
        /// </summary>
        /// <param name="clientId">
        /// </param>
        /// <returns>
        /// </returns>
        public Client GetById(Guid clientId)
        {
            if (this.clients.ContainsKey(clientId))
            {
                return this.clients[clientId];
            }

            return null;
        }

        /// <summary>
        /// The remove.
        /// </summary>
        /// <param name="clientId">
        /// </param>
        public void Remove(Guid clientId)
        {
            lock (this.syncLock)
            {
                this.clients.Remove(clientId);
            }
        }
    }
}